package dao;

import modle.vo.GetGoodsByTypeVO;
import modle.Goods;
import modle.Spec;
import modle.Type;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import util.DruidUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author: ZeYu
 * @Date: 2022/3/15 20:56
 */
public class GoodsDaoImpl implements GoodsDao {
    @Override
    public List<Type> getType() {
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
        List<Type> typeList=null;
        try {
            typeList = queryRunner.query("select id,name from type", new BeanListHandler<Type>(Type.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }return typeList;



    }

    @Override
    public List<GetGoodsByTypeVO> getGoodsTypeId(int typeId) {

        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
        List<GetGoodsByTypeVO>typeVOS= null;
        try {
//            typeVOS = queryRunner.query("select id,image as img name, price,typeId,stockNum from goods where typeId = ? ", new BeanListHandler<GetGoodsByTypeVO>(GetGoodsByTypeVO.class),typeId);
            typeVOS = queryRunner.query("select id,image as img,name,price,typeId,stockNum from goods where typeId = ?", new BeanListHandler<GetGoodsByTypeVO>(GetGoodsByTypeVO.class), typeId);


        } catch (SQLException e) {
            e.printStackTrace();
        }


        return typeVOS;
    }

    @Override
    public void addGoods(Goods goods) {
        QueryRunner runner=new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update("insert into goods values (null,?,?,?,?,?,?)",
                    goods.getName(),
                    goods.getTypeId(),
                    goods.getImage(),
                    goods.getDescription(),
                    goods.getPrice(),
                    goods.getStockNum());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int selectMaxId() {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        Integer query = null;
        try {
            query = runner.query("select max(id) from goods", new ScalarHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public void addSpec(List<Spec> specList) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        for (Spec spec : specList) {
            try {
                runner.update("insert into spec values (null,?,?,?,?)",
                        spec.getSpecName(),
                        spec.getPrice(),
                        spec.getStockNum(),
                        spec.getGoodsId());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
